import 'package:any_reader/public.dart';
import 'package:any_reader/view_model/retrieval_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class RetrievalPage extends StatefulWidget {
  @override
  _RetrievalPageState createState() => _RetrievalPageState();
}

class _RetrievalPageState extends State<RetrievalPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: ProviderWidget<RetrievalModel>(
        model: RetrievalModel(Provider.of<ThemeModel>(context)),
        onModelReady: (model) async => model.initData(),
        builder: (context, model, child) {
          return WillPopScope(
            child: SafeArea(
              child: Scaffold(
                  body: Container(
                child: SmartRefresher(
                  enablePullDown: true,
                  enablePullUp: true,
                  header: MaterialClassicHeader(
                    color: Colors.white,
                    backgroundColor: Colors.black54,
                  ),
                  footer: CustomFooter(
                    loadStyle: LoadStyle.ShowWhenLoading,
                    height: 60,
                    builder: (BuildContext context, LoadStatus mode) {
                      Widget body;
                      if (mode == LoadStatus.idle) {
                        body = Text(
                          "上拉加载",
                          style: TextStyle(
                            color: model
                                .themeModel.customThemeData.mainTextColor
                                .withOpacity(0.5),
                          ),
                        );
                      } else if (mode == LoadStatus.loading) {
                        body = ViewStateLoadingWidget(
                          color: model.themeModel.customThemeData.mainTextColor
                              .withOpacity(0.5),
                        );
                      } else if (mode == LoadStatus.failed) {
                        body = Text("加载失败!",
                            style: TextStyle(
                              color: model
                                  .themeModel.customThemeData.mainTextColor
                                  .withOpacity(0.5),
                            ));
                      } else if (mode == LoadStatus.canLoading) {
                        body = Text("松手,加载更多!",
                            style: TextStyle(
                              color: model
                                  .themeModel.customThemeData.mainTextColor
                                  .withOpacity(0.5),
                            ));
                      } else {
                        body = Text("没有更多数据了!",
                            style: TextStyle(
                              color: model
                                  .themeModel.customThemeData.mainTextColor
                                  .withOpacity(0.5),
                            ));
                      }
                      return Container(
                        height: 55.0,
                        color: model.themeModel.customThemeData.mainColor
                            .withOpacity(0.5),
                        child: Center(child: body),
                      );
                    },
                  ),
                  controller: _refreshController,
                  onRefresh: () async {
                    //我在下拉刷新时执行
                    await model.refresh();
                    // if failed,use refreshFailed()
                    _refreshController.refreshCompleted();
                  },
                  onLoading: () async {
                    //我在上滑加载更多时执行
                    await model.loadMore();
                    _refreshController.loadComplete();
                  },
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        _buildFilter(model, model.bookType, model.setBookType,
                            name: "分类", list: model.bookTypeList),
                        _buildFilter(
                            model, model.bookStatus, model.setBookStatus,
                            name: "状态", list: model.bookStatusList),
                        Container(
                          width: ScreenUtil().setWidth(750 * 0.96),
                          child: Wrap(
                            alignment: WrapAlignment.spaceBetween,
                            crossAxisAlignment: WrapCrossAlignment.start,
                            children: model.busy
                                ? [
                                    Container(
                                      height: ScreenUtil().setHeight(500),
                                      child: Center(
                                        child: ViewStateLoadingWidget(
                                          color: model.themeModel
                                              .customThemeData.mainTextColor
                                              .withOpacity(0.5),
                                        ),
                                      ),
                                    )
                                  ]
                                : model.list.length > 0
                                    ? model.list
                                        .map((item) =>
                                            _buildBookItem(model, item: item))
                                        .toList()
                                    : [
                                        Container(
                                          child: Center(
                                            child: ViewStateEmptyWidget(
                                              buttonText: Text(""),
                                            ),
                                          ),
                                        )
                                      ],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              )),
            ),
          );
        },
      ),
    );
  }

  Widget _buildBookItem(RetrievalModel model, {Book item}) {
    return InkWell(
      onTap: () {
        String title = Uri.encodeComponent(item.title) ?? "";
        String url = Uri.encodeComponent(item.originUrl) ?? "";
        String author = Uri.encodeComponent(item.author) ?? "";
        String reptileType = Uri.encodeComponent(item.reptileType) ?? "";
        String reptileType1 = Uri.encodeComponent(item.reptileType1) ?? "";
        String now = "0";
        var route = "/book_info?"
            "title=$title&"
            "author=$author&"
            "url=$url&"
            "now=$now&"
            "reptileType=$reptileType&"
            "reptileType1=$reptileType1&";
        AppConfig.router
            .navigateTo(context, route, transition: TransitionType.inFromRight);
      },
      child: Container(
        width: ScreenUtil().setWidth(750 * 0.85 / 3),
        margin: EdgeInsets.fromLTRB(
          ScreenUtil().setHeight(10),
          ScreenUtil().setHeight(20),
          ScreenUtil().setHeight(10),
          ScreenUtil().setHeight(5),
        ),
        child: Column(
          children: <Widget>[
            Container(
              height: ScreenUtil().setHeight(1334 / 5),
              width: ScreenUtil().setWidth(750 * 0.85 / 3),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(ScreenUtil().setWidth(5)),
                child: Stack(
                  fit: StackFit.expand,
                  children: <Widget>[
                    CachedImage(
                      url: item.bookId != null
                          ? AppConfig.IMG_BASE_UEL.toString() +
                              "images/" +
                              item.bookId.toString()
                          : item.imgUrl,
                      fit: BoxFit.cover,
                    ),
                    Positioned(
                      left: 0,
                      top: 0,
                      height: ScreenUtil().setHeight(1334 / 5),
                      width: ScreenUtil().setWidth(750 * 0.85 / 3),
                      child: Container(
                        color: Color.fromARGB(40, 0, 0, 0),
                      ),
                    )
                  ],
                ),
              ),
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: Text(
                item.title,
                maxLines: 1,
                textAlign: TextAlign.left,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: model.themeModel.customThemeData.mainTextColor
                      .withOpacity(0.6),
                  fontSize: ScreenUtil().setSp(24, allowFontScalingSelf: true),
                ),
              ),
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: Text(
                "${item.bookType}",
                maxLines: 1,
                textAlign: TextAlign.left,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: model.themeModel.customThemeData.mainBackgroundColor,
                  fontSize: ScreenUtil().setSp(18, allowFontScalingSelf: true),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildFilter(RetrievalModel model, String key, Function cb,
      {name: "分类", list}) {
    return Container(
      padding: EdgeInsets.symmetric(
        vertical: ScreenUtil().setHeight(10),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            width: ScreenUtil().setWidth(150),
            alignment: Alignment.center,
            margin: EdgeInsets.symmetric(
              vertical: ScreenUtil().setWidth(10),
            ),
            child: Text(
              name + " :",
              style: TextStyle(
                color: model.themeModel.customThemeData.mainTextColor
                    .withOpacity(0.9),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Wrap(
              alignment: WrapAlignment.start,
              spacing: ScreenUtil().setWidth(10),
              children: _buildList(model, key, cb, list),
            ),
          )
        ],
      ),
    );
  }

  List<Widget> _buildList(RetrievalModel model, String key, Function cb,
      List<Map<String, dynamic>> list) {
    List<Widget> _list = [];

    for (int i = 0; i < list.length; i++) {
      _list.add(GestureDetector(
        onTap: () {
          cb(i);
        },
        child: Container(
          margin: EdgeInsets.symmetric(
            vertical: ScreenUtil().setWidth(10),
            horizontal: ScreenUtil().setWidth(10),
          ),
          child: Text(
            list[i]['name'],
            style: TextStyle(
              color: key == list[i]['id']
                  ? model.themeModel.customThemeData.mainTextColor.withRed(100)
                  : model.themeModel.customThemeData.mainTextColor
                      .withOpacity(0.5),
            ),
          ),
        ),
      ));
    }
    return _list;
  }
}
